package cn.csust.net2.manager.client.Interaction;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.csust.net2.manager.client.app.App;
import cn.csust.net2.manager.client.panel.NoticeManagePanel;
import cn.csust.net2.manager.client.ux.BeanGrid;
import cn.csust.net2.manager.client.ux.ExpandTree;
import cn.csust.net2.manager.shared.po.Banji;
import cn.csust.net2.manager.shared.po.Notice;
import cn.csust.net2.manager.shared.po.Teacher;
import cn.csust.net2.manager.shared.service.ByGradeService;
import cn.csust.net2.manager.shared.service.ByGradeServiceAsync;
import cn.csust.net2.manager.shared.service.NoticeManagerService;
import cn.csust.net2.manager.shared.service.NoticeManagerServiceAsync;
import cn.csust.net2.manager.shared.vo.Config;
import cn.csust.net2.manager.shared.vo.TreeNode;

import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.HtmlEditor;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
 * 
 * 发布公告窗口
 * @author Administrator
 *
 */
public class NoticeWriteWindow extends Window{

	private NoticeManagerServiceAsync noticeManagerService;
	private ByGradeServiceAsync service ;
	private ExpandTree treePanel;
	
	
	public NoticeManagePanel noticeManagePanel;

	private Notice notice;
	private BeanGrid<Notice> grid;

	
	TextField<String> titleFiled;
	TextField<String> senderFiled;
	DateField startDateFiled ;
	DateField endDateFiled;
	HtmlEditor content ;
	
	public NoticeWriteWindow() {
		this.setSize(600, 500);
		this.setLayout(new BorderLayout());
		this.setLayoutOnChange(true);
		init();
	}

	private void init(){
		
		service = GWT.create(ByGradeService.class);	
		noticeManagerService = GWT.create(NoticeManagerService.class);	

		 
		
		FormPanel panel = new FormPanel();   
	    panel.setBorders(false);   
	    panel.setBodyBorder(false);   
	    panel.setLabelWidth(55);   
	    panel.setPadding(5);   
	    panel.setHeaderVisible(false);   
	  
	    titleFiled = new TextField<String>();  
	    titleFiled.setFieldLabel("主题"); 
	    titleFiled.setName("noticeTitle");
	    panel.add(titleFiled); 
	  
	    startDateFiled = new DateField();
	    startDateFiled.setName("startDate");
	    startDateFiled.setFieldLabel("发送时间");  
	    startDateFiled.setAutoValidate(true);
	    panel.add(startDateFiled);  
	    
	    endDateFiled = new DateField();
	    endDateFiled.setName("endDate");
	    endDateFiled.setFieldLabel("过期时间"); 
	    endDateFiled.setAutoValidate(true);
	    panel.add(endDateFiled);   
	  
	    content = new HtmlEditor(); 
	    content.setName("noticeContent");
	    content.setHideLabel(true);
	    panel.add(content, new FormData("100% -53"));   
	    
	    Button submit = new Button("提交");
	    submit.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				
				if(titleFiled.getValue()==null||titleFiled.getValue().trim()==""){
					MessageBox.alert("消息", "主题不能为空", null);
					return;
				}
				
				if(notice==null){
					if(treePanel.tree.getCheckedSelection().size()==0){
						MessageBox.alert("消息", "没有选择发送人", null);
						return;
					}
					save();
				}else{
					modify();
				}
				
			}
	    	
	    });
		Button reset = new Button("重置");
		reset.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				if(notice==null){
					titleFiled.setValue(null);
					startDateFiled.setValue(null);
					endDateFiled.setValue(null);
					content.setValue(null);
					treePanel.tree.setCheckedSelection(null);
				}else{
					titleFiled.setValue(notice.getNoticeTitle());
					startDateFiled.setValue(notice.getStartDate());
					endDateFiled.setValue(notice.getEndDate());
					content.setValue(notice.getNoticeContent());
					BeanModelFactory beanModelFactory = BeanModelLookup.get().getFactory(Banji.class);
					BeanModel model = beanModelFactory.createModel(notice.getBanji());
					treePanel.tree.setChecked(model, true);
				}
				
			}
	    	
	    });
		panel.addButton(submit);
		panel.addButton(reset);	  
		
	    BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);    
	    centerData.setMargins(new Margins(0)); 
	    this.add(panel, centerData);
	    
	    initTree();
		BorderLayoutData eastData = new BorderLayoutData(LayoutRegion.EAST, 200);  
		this.add(treePanel, eastData);
	    
		
	}
	
	
	//发布公告
	private void save(){

		notice = new Notice();
		notice.setNoticeTitle(titleFiled.getValue());
		notice.setSender((Teacher)App.getUser());
		notice.setStartDate(startDateFiled.getValue());
		notice.setEndDate(endDateFiled.getValue());
		notice.setNoticeContent(content.getValue());
		try {
			for (BeanModel item : treePanel.tree.getCheckedSelection()) {				
			 	TreeNode node = item.getBean();
			 	if(node instanceof Banji){
			 		Banji banji = (Banji)node;
			 		notice.setBanji(banji);

					noticeManagerService.save(notice, new AsyncCallback<Void>() {
						
						@Override
						public void onSuccess(Void result) {
							// TODO Auto-generated method stub
						
							grid = noticeManagePanel.getNoticeGridPanel().getGrid();
							
							Config loadConfig = new Config();
							loadConfig.put("student", App.getUser());
							noticeManagePanel.getNoticeGridPanel().load(loadConfig);
							grid.getView().refresh(true);

						}
						
						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
							
						}
					});

			 	}
			 	
			}
			
			MessageBox.alert("消息", "保存成功", null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			MessageBox.alert("消息", "发送失败", null);
			e.printStackTrace();
			
		}
		
	}
	
	
	//修改公告
	private void modify(){
		notice.setNoticeTitle(titleFiled.getValue());
		notice.setSender((Teacher)App.getUser());
		notice.setStartDate(startDateFiled.getValue());
		notice.setEndDate(endDateFiled.getValue());
		notice.setNoticeContent(content.getValue());
		
		try {
			noticeManagerService.update(notice, new AsyncCallback<Void>(){

				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onSuccess(Void result) {
					// TODO Auto-generated method stub
					grid = noticeManagePanel.getNoticeGridPanel().getGrid();
					BeanModelFactory beanModelFactory = BeanModelLookup.get().getFactory(Notice.class);
					BeanModel model = beanModelFactory.createModel(notice);
					grid.getStore().update(model);
					grid.getView().refresh(true);
					
				}
				
			});
			MessageBox.alert("消息", "修改成功", null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			MessageBox.alert("消息", "修改失败", null);
		}
	}
	
	
	//用户树初始化
	private void initTree(){
		Map <String ,Object> map = new HashMap<String , Object>();
		map.put(ExpandTree.TEACHER_ADD, false);
		map.put(ExpandTree.CHECKABLE, true);
		treePanel = new ExpandTree(Banji.class,true,map){
			@Override
			protected void load(Object loadConfig,Map<String,Object> configs,AsyncCallback<List<TreeNode>> callback) {
				
				service.getChildren((TreeNode)loadConfig,configs, callback);
			}

			@Override
			protected void load(String[] items) {
				
				Config c = new Config();
				c.put(ExpandTree.GRADE_ITEMS, items);
				treePanel.load(Banji.class,c);
			}
			
		};
		
	}
	
	
	
	public void recreateWindow(){
		this.remove(treePanel);
	}


	public TextField<String> getTitleFiled() {
		return titleFiled;
	}

	public void setTitleFiled(TextField<String> titleFiled) {
		this.titleFiled = titleFiled;
	}

	public DateField getStartDateFiled() {
		return startDateFiled;
	}

	public void setStartDateFiled(DateField startDateFiled) {
		this.startDateFiled = startDateFiled;
	}

	public DateField getEndDateFiled() {
		return endDateFiled;
	}

	public void setEndDateFiled(DateField endDateFiled) {
		this.endDateFiled = endDateFiled;
	}

	public HtmlEditor getContent() {
		return content;
	}

	public void setContent(HtmlEditor content) {
		this.content = content;
	}

	public ExpandTree getTreePanel() {
		return treePanel;
	}

	public void setTreePanel(ExpandTree treePanel) {
		this.treePanel = treePanel;
	}

	public Notice getNotice() {
		return notice;
	}

	public void setNotice(Notice notice) {
		this.notice = notice;
	}
	
	
}
